import json
import difflib
import pprint
from src.find_kv_and_check_word.tools_hyc_cyy import get_different_kvs_based_group
import json
import re
from src.tools.dms_operator import dmsoperator
from typing import List, Union

##################### required #####################
def get_dict_by_id(file_id,_list):
    for item in _list:
        if item['file_id'] == file_id:
            return item

def get_annotations(kv_results, file_id, result, document_name):
    annotation_results = result
    kv_results_list = kv_results

    sourse_file_id = file_id

    annotation_list = []
    for kv in get_dict_by_id(sourse_file_id,kv_results_list)['kv_json']:
        kv_index = kv['kv_index']
        str = ""
        for item in annotation_results['result']:
            if item['sourse_file_id'] == sourse_file_id:
                target_file_id = item['target_file_id']
                for compare_result in item['compare_result']:
                    # print(f"kv_index={kv_index}")
                    # pprint.pprint(compare_result)
                    if compare_result['sourse']['index'] == kv_index:
                        # 排除similarty_score符合但是拥有相同value的项
                        if compare_result['sourse']['value'] == compare_result['target']['value']:
                            str += f"与《{document_name[item['target_file_id']]}》中{compare_result['target']['object']}{compare_result['target']['value']}一致、"
                        else: str += f"与《{document_name[item['target_file_id']]}》中{compare_result['target']['object']}{compare_result['target']['value']}不一致、"
        annotation_list.append(str)
    print(annotation_list)
    return annotation_list

def append_data(file_id_list: List[str], more_keywords: str, single_file_flag: bool, task_id: Union[str, int], file_info: dict) -> List[List[dict]]:
    # 存储处理后的md_results, kv_results和values_based_results
    md_results_list = []
    kv_results_list = []
    values_based_results_list = []
    
    # 输出文件ID列表，便于调试
    pprint.pprint(file_id_list)

    # 遍历文件ID列表
    for file_id in file_id_list:
        print("获取单份文档的关键词和对应值......")
        print(f'来自前端的文件ID:{file_id}')
        print(f'来自指标库的关键字:{more_keywords}')
        
        # 获取当前文件的键值对数据，单文档时有三个Dict2str，多文档时只有两个Dict2str
        result = get_different_kvs_based_group(file_id, more_keywords, single_file_flag, task_id, file_info)
        
        if result['code'] == 500:
            raise Exception(result['info'])
        
        data_list = result['data']
        
        # 输出当前文件的键值对数据，便于调试
        pprint.pprint(data_list)
        
         # 如果当前文档没有关键词和对应值，跳过后续处理
        if data_list == "null":
            # continue
            # 如果单文档检查时没有关键词，或者多文档检查时，主文档没有关键词，则直接略过后续操作
            return [md_results_list, kv_results_list, values_based_results_list]

        # 处理md_json数据
        try:
            md_results = json.loads(data_list[0])  # 将字符串转为JSON对象
            md_results['file_id'] = file_id  # 添加文件ID
            md_results_list.append(md_results)  # 将处理结果添加到md_results_list列表
            # # 每次更新md_results.json文件时，保持数据的完整性
            # with open(r'src\find_kv_and_check_word\test_json\md_results.json', 'w', encoding='UTF-8') as file:
            #     json.dump(md_results_list, file, ensure_ascii=False, indent=2)
        except Exception as e:
            # 如果处理md_json时出现错误，输出错误信息
            print(f"处理md_json时发生错误: {e}")

        # 处理kv_json数据
        try:
            kv_results = json.loads(data_list[1])  # 将字符串转为JSON对象
            kv_results['file_id'] = file_id  # 添加文件ID
            kv_results_list.append(kv_results)  # 将处理结果添加到kv_results_list列表
            # # 每次更新kv_results.json文件时，保持数据的完整性
            # with open(r'src\find_kv_and_check_word\kv_results.json', 'w', encoding='UTF-8') as file:
            #     json.dump(kv_results_list, file, ensure_ascii=False, indent=2)
        except Exception as e:
            # 如果处理kv_json时出现错误，输出错误信息
            print(f"处理kv_json时发生错误: {e}")
            
        # 如果时单文档，则有三个Dict2str，进入以下流程
        if single_file_flag:
            # 处理values_based_results数据
            try:
                values_based_results = json.loads(data_list[2])  # 将字符串转为JSON对象
                values_based_results['file_id'] = file_id  # 添加文件ID
                values_based_results_list.append(values_based_results)  # 将处理结果添加到values_based_results_list列表
                # # 每次更新values_based_results.json文件时，保持数据的完整性
                # with open(r'src\find_kv_and_check_word\test_json\values_based_results.json', 'w', encoding='UTF-8') as file:
                #     json.dump(values_based_results_list, file, ensure_ascii=False, indent=2)
            except Exception as e:
                # 如果处理values_based_results时出现错误，输出错误信息
                print(f"处理values_based_results时发生错误: {e}")

    # 返回所有处理后的结果
    return [md_results_list, kv_results_list, values_based_results_list]

def is_fourth_level_title(list_text):
    '''
    检查是否为四级标题
    '''
    return re.match(r'^[a-z]\.$', list_text) is not None

def is_third_level_title(list_text):
    '''
    检查是否为三级标题
    '''
    return re.match(r'^\d+\.\d+\.\d+\.$', list_text) is not None

def is_second_level_title(list_text):
    '''
    检查是否为二级标题
    '''
    return re.match(r'^\d+\.\d+\.$', list_text) is not None

def is_first_level_title(list_text):
    '''
    检查是否为一级标题
    '''
    return re.match(r'^\d+\.$', list_text) is not None

def is_major_title(list_text):
    '''
    检查是否为大标题
    '''
    pattern = r'^(一|二|三|四|五|六|七|八|九|十|十一|十二|十三|十四|十五|十六|十七|十八|十九|二十)、$'
    return re.match(pattern, list_text) is not None

def find_previous_titles(index, index_map):
    '''
    向前查找合适的标题
    '''
    major_title = None
    first_level_title = None
    second_level_title = None
    third_level_title = None
    major_title_flag = 1
    first_level_title_flag = 1
    second_level_title_flag = 1
    third_level_title_flag = 1

    current_index = index
    while current_index > 0:
        current_index -= 1
        if current_index in index_map:
            prev_paragraph = index_map[current_index]
            prev_list_text = prev_paragraph.get('listText')
            if is_major_title(prev_list_text) and major_title_flag == 1:
                major_title = prev_paragraph['listText'] + prev_paragraph['text']
                major_title_flag = 0
            elif is_first_level_title(prev_list_text) and first_level_title_flag == 1:
                first_level_title = prev_paragraph['listText']
                first_level_title_flag = 0
            elif is_second_level_title(prev_list_text) and second_level_title_flag == 1:
                second_level_title = prev_paragraph['listText']
                second_level_title_flag = 0
            elif is_third_level_title(prev_list_text) and third_level_title_flag == 1:
                third_level_title = prev_paragraph['listText']
                third_level_title_flag = 0
            if major_title_flag == 0:
                break

    return major_title, first_level_title, second_level_title, third_level_title

def extract_conditions(kv_results):
    '''
    解析kv_results.json对象中的匹配条件
    '''
    # 加载JSON文件
    kv_result_data = kv_results

    conditions = []
    for item in kv_result_data:
        for kv_item in item['kv_json']:
            conditions.append({
                'kv_index': kv_item['kv_index'],
                'index': kv_item['value'][0]['index'],
                'sectionIndex': kv_item['value'][0]['sectionIndex'],
                'bodyChildIndex': kv_item['value'][0]['bodyChildIndex']
            })
    return conditions

def extract_text(kv_results):
    '''
    根据匹配条件从1_result.json对象中提取数据
    '''
    
    # 获取匹配条件
    conditions = extract_conditions(kv_results)
    # 加载JSON文件
    json_content = dmsoperator.get_jsonfile(kv_results[0]['file_id'])

    result = []
    index_map = {p['index']: p for p in json_content['paragraphInfos']}

    for condition in conditions:
        if condition['index'] in index_map:
            paragraph = index_map[condition['index']]
            if (paragraph['sectionIndex'] == condition['sectionIndex'] and
                    paragraph['bodyChildIndex'] == condition['bodyChildIndex']):
                list_text = paragraph.get('listText', '')
                if is_fourth_level_title(list_text) or list_text == '':
                    # 向前查找合适的标题
                    major_title, first_level_title, second_level_title, third_level_title = find_previous_titles(
                        condition['index'], index_map)
                    formatted_title = f"{major_title}{third_level_title or ''}"
                    result.append({'kv_index': condition['kv_index'], 'value': formatted_title})
                elif is_third_level_title(list_text):
                    # 向前查找合适的标题
                    major_title, first_level_title, second_level_title, third_level_title = find_previous_titles(
                        condition['index'], index_map)
                    result.append({'kv_index': condition['kv_index'], 'value': f"{major_title}" + paragraph['listText']})
                elif is_second_level_title(list_text):
                    # 向前查找合适的标题
                    major_title, first_level_title, second_level_title, third_level_title = find_previous_titles(
                        condition['index'], index_map)
                    result.append(
                        {'kv_index': condition['kv_index'], 'value': f"{major_title}" + paragraph['listText']})
                elif is_first_level_title(list_text):
                    # 向前查找合适的标题
                    major_title, first_level_title, second_level_title, third_level_title = find_previous_titles(
                        condition['index'], index_map)
                    result.append(
                        {'kv_index': condition['kv_index'], 'value': f"{major_title}" + paragraph['listText']})
                else:
                    result.append(
                        {'kv_index': condition['kv_index'], 'value': paragraph['listText'] + paragraph['text']})
        else:
            # 如果匹配到的段落在 tableInfos 中
            table_info = next((t for t in json_content['tableInfos'] if
                               t['index'] == condition['index'] and
                               t['sectionIndex'] == condition['sectionIndex'] and
                               t['bodyChildIndex'] == condition['bodyChildIndex']), None)
            if table_info:
                # 向前查找合适的标题
                major_title, first_level_title, second_level_title, third_level_title = find_previous_titles(
                    condition['index'], index_map)
                if third_level_title is not None:
                    formatted_title = f"{major_title}{third_level_title}"
                    result.append(
                        {'kv_index': condition['kv_index'], 'value': formatted_title})
                elif second_level_title is not None:
                    formatted_title = f"{major_title}{second_level_title}"
                    result.append(
                        {'kv_index': condition['kv_index'], 'value': formatted_title})
                elif first_level_title is not None:
                    formatted_title = f"{major_title}{first_level_title}"
                    result.append(
                        {'kv_index': condition['kv_index'], 'value': formatted_title})
                else:
                    result.append(
                        {'kv_index': condition['kv_index'], 'value': major_title})
    return result

##################### optional #####################
def read_json_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        return json.load(file)

def load_json_version_1(file_path):
    try: 
        with open(file_path, 'r', encoding='UTF-8') as file:
            data = json.load(file)
    except FileNotFoundError:
        print("文件路径不存在: "+file_path)
    except json.JSONDecodeError:
        print("json文件解析失败")
    else:
        return data

def load_json_version_2(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return json.load(file)
    except FileNotFoundError:
        print(f"文件未找到: {file_path}")
        return None
    except json.JSONDecodeError as e:
        print(f"JSON解码错误: {e} in file {file_path}")
        return None
   
def write_json(final, md_results, kv_results, values_based_results):
    with open(md_results, 'w', encoding="UTF-8") as file:
        json.dump(final[0], file, ensure_ascii=False, indent=4)
    with open(kv_results, 'w', encoding="UTF-8") as file:
        json.dump(final[1], file, ensure_ascii=False, indent=4)
    with open(values_based_results, 'w', encoding="UTF-8") as file:
        json.dump(final[2], file, ensure_ascii=False, indent=4)
        
def calculate_similarity(str1, str2):
    """
    计算两个字符串的相似度

    :param str1: 第一个字符串
    :param str2: 第二个字符串
    :return: 相似度分数（0.0 到 1.0 之间）
    """
    matcher = difflib.SequenceMatcher(None, str1, str2)
    similarity_ratio = matcher.ratio()
    return similarity_ratio
